package sms

import (
	"log"
	"regexp"
	"sync"

	"goskeleton/app/global/variable"
)

// 短信中心
var (
	regStrCmpp string
	regStrSgip string
	regStrSmgp string
	regPtrCmpp *regexp.Regexp
	regPtrSgip *regexp.Regexp
	regPtrSmgp *regexp.Regexp
	lock       sync.Mutex
)

func SplitPhones(phones []string) [][]string {
	// 0- 移动；1- 联通；2-电信
	smc := make([][]string, 3, 3)
	if len(phones) == 0 {
		return smc
	} else {
		smc[0] = make([]string, 0)
		smc[1] = make([]string, 0)
		smc[2] = make([]string, 0)
	}
	preCompile(0)
	preCompile(1)
	preCompile(2)

	for i := 0; i < len(phones); i++ {
		if regPtrCmpp.Match([]byte(phones[i])) {
			smc[0] = append(smc[0], phones[i])
		} else if regPtrSgip.Match([]byte(phones[i])) {
			smc[1] = append(smc[1], phones[i])
		} else if regPtrSmgp.Match([]byte(phones[i])) {
			smc[2] = append(smc[2], phones[i])
		}
	}
	return smc
}

func preCompile(smc int) {
	lock.Lock()
	defer lock.Unlock()

	var seg string
	var flag bool
	switch smc {
	case 0:
		seg = variable.SmcConfigYml.GetString("cmpp.segment")
		flag = seg != regStrCmpp && len(seg) > 0
	case 1:
		seg = variable.SmcConfigYml.GetString("sgip.segment")
		flag = seg != regStrSgip && len(seg) > 0
	case 2:
		seg = variable.SmcConfigYml.GetString("smgp.segment")
		flag = seg != regStrSmgp && len(seg) > 0
	}

	if flag {
		ptr, err := regexp.Compile(seg)
		if err == nil {
			switch smc {
			case 0:
				regPtrCmpp = ptr
				regStrCmpp = seg
			case 1:
				regPtrSgip = ptr
				regStrSgip = seg
			case 2:
				regPtrSmgp = ptr
				regStrSmgp = seg
			}
		} else {
			log.Fatalf("正则表达式编译失败: %v", err)
		}
	}
}
